package com.xca.znb.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.xca.znb.contact.GoodsDetailContact;
import com.xca.znb.entity.Collect;
import com.xca.znb.entity.Goods;
import com.xca.znb.model.impl.GoodsDetailImpl;
import com.xca.znb.presenter.GoodsDetailsPresenter;

import org.json.JSONArray;
import org.json.JSONException;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class GoodsDetailActivity extends AppCompatActivity implements View.OnClickListener , GoodsDetailContact {
    private BottomSheetDialog bottomSheetDialog;
    private ImageButton Back , ShoppingCart  ;
    private ImageButton EnterStore , AddShoppingCart , BuyNow ;
    private ImageView TitlePhoto , ShowConcern ;
    private TextView ShowPrice ,  ShowUnit , ShowLocal , ShowLogistics , ShowId,
            ShowName , ShowDetails , ShowGoodsName;
    private LinearLayout EnterStores , AskUser , CallPhone ;
    private ListView listPhotos ;
    private ArrayList<String> imageList  = new ArrayList<>();
    private CheckBox addCollection ;
    private ArrayAdapter<String> adapter ;

    private GoodsDetailsPresenter presenter ;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_activity);
        Back = findViewById(R.id.goods_enter_back);
        ShoppingCart = findViewById(R.id.enter_shopping_cart);
        EnterStore = findViewById(R.id.detail_enter_store);
        AddShoppingCart = findViewById(R.id.add_shopping_cart);
        BuyNow = findViewById(R.id.buy_now);
        TitlePhoto = findViewById(R.id.title_photo_show);
        ShowConcern = findViewById(R.id.detail_show_concern);
        ShowPrice = findViewById(R.id.show_price_goods);
        ShowLocal = findViewById(R.id.detail_show_local);
        ShowLogistics = findViewById(R.id.detail_show_logistics);
        ShowName = findViewById(R.id.detail_show_name);
        ShowDetails = findViewById(R.id.show_details);
        EnterStores = findViewById(R.id.enter_store_bottom);
        AskUser = findViewById(R.id.detail_ask);
        CallPhone = findViewById(R.id.detail_call);
        listPhotos = findViewById(R.id.detail_show_photos);

        ShowUnit = findViewById(R.id.show_unit_goods) ;
        addCollection = findViewById(R.id.radio_goods_add_collection);
        ShowId = findViewById(R.id.show_id_goods);
        ShowGoodsName = findViewById(R.id.show_goods_name_detail);

        GoodsDetailImpl goodsDetail = new GoodsDetailImpl(this);
        presenter = new GoodsDetailsPresenter(this,goodsDetail);

        Intent intent = getIntent();
        String getGoodsId = intent.getStringExtra("goodsId") ;
        try {
            int goodsId = Integer.parseInt(getGoodsId);
            presenter.goodsDetails(goodsId);
        } catch (NumberFormatException e) {
            // 处理异常，例如设置默认值或者显示错误信息
            e.printStackTrace();
        }

        Back.setOnClickListener(this);
        AddShoppingCart.setOnClickListener(this);
        BuyNow.setOnClickListener(this);
        EnterStore.setOnClickListener(this);
        EnterStores.setOnClickListener(this);
        CallPhone.setOnClickListener(this);
        AskUser.setOnClickListener(this);
        addCollection.setOnClickListener(this);
        ShoppingCart.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.goods_enter_back){
            onBackPressed();
        } else if (v.getId() == R.id.enter_shopping_cart) {
            Intent intent = new Intent(GoodsDetailActivity.this , ShoppingCartActivity.class);
            startActivity(intent);
        }else if (v.getId() == R.id.detail_enter_store) {
            Intent intent1 = getIntent();
            String getGoodsId = intent1.getStringExtra("goodsId") ;


            Intent intent = new Intent(GoodsDetailActivity.this , EnterStoreActivity.class);

            int goodsId = Integer.parseInt(getGoodsId);
            Goods goods = presenter.getGoodsById(goodsId);
            String publisherPhone = goods.getPublisher() ;
            intent.putExtra("salesPhone" , publisherPhone);
            startActivity(intent);
        }else if (v.getId() == R.id.add_shopping_cart) {
            Intent intent1 = getIntent();
            String getGoodsId = intent1.getStringExtra("goodsId") ;
            Goods goods = presenter.getGoodsById(Integer.parseInt(getGoodsId));
            if (goods.getState().equals("上架中")){
                showBottomSheet1();
            } else if (goods.getState().equals("已下架")) {
                Toast.makeText(this, "该商品已下架，看看其他商品吧", Toast.LENGTH_SHORT).show();
            } else if (goods.getState().equals("已删除")) {
                Toast.makeText(this, "该商品已删除，看看其他商品吧", Toast.LENGTH_SHORT).show();
            }
        }else if (v.getId() == R.id.buy_now) {
            Intent intent1 = getIntent();
            String getGoodsId = intent1.getStringExtra("goodsId") ;
            Goods goods = presenter.getGoodsById(Integer.parseInt(getGoodsId));
            if (goods.getState().equals("上架中")){
                showBottomSheet2();
            } else if (goods.getState().equals("已下架")) {
                Toast.makeText(this, "该商品已下架，看看其他商品吧", Toast.LENGTH_SHORT).show();
            } else if (goods.getState().equals("已删除")) {
                Toast.makeText(this, "该商品已删除，看看其他商品吧", Toast.LENGTH_SHORT).show();
            }

        }else if (v.getId() == R.id.enter_store_bottom) {
            Intent intent1 = getIntent();
            String getGoodsId = intent1.getStringExtra("goodsId") ;


            Intent intent = new Intent(GoodsDetailActivity.this , EnterStoreActivity.class);

            int goodsId = Integer.parseInt(getGoodsId);
            Goods goods = presenter.getGoodsById(goodsId);
            String publisherPhone = goods.getPublisher() ;
            intent.putExtra("salesPhone" , publisherPhone);
            startActivity(intent);
        }else if (v.getId() == R.id.detail_ask) {
            //获取当前时间：精确到秒
            LocalDateTime nowTime = LocalDateTime.now();
            String secTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            Intent intent = getIntent();
            String getGoodsId = intent.getStringExtra("goodsId") ;
            try {
                int goodsId = Integer.parseInt(getGoodsId);
                Goods goods = presenter.getGoodsById(goodsId);

                SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                String phone = sharedPreferences.getString("phone" , "");
                presenter.addNewsletter(phone,goods.getPublisher(),secTime);
                Intent intent1 = new Intent(GoodsDetailActivity.this , MessageActivity.class) ;
                intent1.putExtra("goods_send" , phone);
                intent1.putExtra("goods_receive" , goods.getPublisher());
                startActivity(intent1);
            } catch (NumberFormatException e) {
                // 处理异常，例如设置默认值或者显示错误信息
                e.printStackTrace();
            }

        }else if (v.getId() == R.id.detail_call) {
            Intent intent = getIntent();
            String getGoodsId = intent.getStringExtra("goodsId") ;
            try {
                int goodsId = Integer.parseInt(getGoodsId);
                String phoneNumber = presenter.getGoodsById(goodsId).getPublisher();
                showCallConfirmationDialog(phoneNumber); // 替换为实际电话号码
            } catch (NumberFormatException e) {
                // 处理异常，例如设置默认值或者显示错误信息
                e.printStackTrace();
            }
        } else if (v.getId() == R.id.radio_goods_add_collection) {
            String type = "goods" ;//收藏类型
            SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
            String phone = sharedPreferences.getString("phone" , "");//收藏user
            Intent intent = getIntent();
            String getGoodsId = intent.getStringExtra("goodsId") ;
            int goodsId = Integer.parseInt(getGoodsId);
            String gId = String.valueOf(goodsId);//收藏id
            Collect collect = presenter.getCollect(gId,type,phone);
            if (addCollection.isChecked()){
                if (collect == null){
                    presenter.addCollect(gId,type,phone);
                    Collect collect1 = presenter.getCollect(gId,type,phone);
                    if (collect1 != null){
                        Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
                    }
                }
            }else {
                if (collect != null){
                    presenter.delCollect(collect.getId());
                    Collect collect1 = presenter.getCollect(gId,type,phone);
                    if (collect1 == null){
                        Toast.makeText(this, "取消收藏", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
    private void showBottomSheet1(){
        bottomSheetDialog = new BottomSheetDialog(GoodsDetailActivity.this) ;
        bottomSheetDialog.setContentView(R.layout.buy_chance_specs);
        ImageView goodsImg = bottomSheetDialog.findViewById(R.id.buy_chance_img);
        TextView price = bottomSheetDialog.findViewById(R.id.buy_chance_price);
        TextView unit = bottomSheetDialog.findViewById(R.id.buy_chance_unit);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.no_buy_goods) ;
        ImageButton Subtract = bottomSheetDialog.findViewById(R.id.subtract_one);
        ImageButton Add = bottomSheetDialog.findViewById(R.id.add_one) ;
        EditText Need = bottomSheetDialog.findViewById(R.id.need_number) ;
        TextView Total = bottomSheetDialog.findViewById(R.id.show_total) ;
        Button Sure = bottomSheetDialog.findViewById(R.id.add_sure) ;

        Intent intent = getIntent();
        String getGoodsId = intent.getStringExtra("goodsId") ;
        int goodsId = Integer.parseInt(getGoodsId);
        Goods goods = presenter.getGoodsById(goodsId);
        Glide.with(GoodsDetailActivity.this)
                        .load(goods.getFirst_image())
                                .into(goodsImg);
        price.setText(String.valueOf(goods.getPrice()));
        unit.setText(goods.getUnit());
        Total.setText(String.valueOf(goods.getPrice()));
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        Need.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s!=null && !s.toString().isEmpty()){
                    int num = Integer.parseInt(Need.getText().toString());
                    if (num<=1000){
                        Total.setText(String.valueOf(goods.getPrice() * num));
                    }else {
                        Total.setText(String.valueOf(goods.getPrice()*1000));
                        Toast.makeText(GoodsDetailActivity.this, "超过购买数量", Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Total.setText("0");
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        Subtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String num = Need.getText().toString();
                int number = Integer.parseInt(num);
                if (number>1){
                    Need.setText(String.valueOf(number-1));
                    Total.setText(String.valueOf(goods.getPrice() * (number-1)));
                }else {
                    Toast.makeText(GoodsDetailActivity.this, "亲，不能再少了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String num = Need.getText().toString();
                int number = Integer.parseInt(num);
                if (number<=1000){
                    Need.setText(String.valueOf(number+1));
                    Total.setText(String.valueOf(goods.getPrice() * (number+1)));
                }else {
                    Total.setText(String.valueOf(goods.getPrice()*1000));
                    Need.setText("1000");
                    Toast.makeText(GoodsDetailActivity.this, "超过购买数量", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        Sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = Integer.parseInt(Need.getText().toString());
                presenter.addCart(goodsId , num , phone);
                bottomSheetDialog.dismiss();
                Toast.makeText(GoodsDetailActivity.this, "已添加购物车", Toast.LENGTH_SHORT).show();
            }
        });
        bottomSheetDialog.show();
    }
    private void showBottomSheet2(){
        bottomSheetDialog = new BottomSheetDialog(GoodsDetailActivity.this) ;
        bottomSheetDialog.setContentView(R.layout.buy_chance_specs);
        ImageView goodsImg = bottomSheetDialog.findViewById(R.id.buy_chance_img);
        TextView price = bottomSheetDialog.findViewById(R.id.buy_chance_price);
        TextView unit = bottomSheetDialog.findViewById(R.id.buy_chance_unit);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.no_buy_goods) ;
        ImageButton Subtract = bottomSheetDialog.findViewById(R.id.subtract_one);
        ImageButton Add = bottomSheetDialog.findViewById(R.id.add_one) ;
        EditText Need = bottomSheetDialog.findViewById(R.id.need_number) ;
        TextView Total = bottomSheetDialog.findViewById(R.id.show_total) ;
        Button Sure = bottomSheetDialog.findViewById(R.id.add_sure) ;

        Intent intent = getIntent();
        String getGoodsId = intent.getStringExtra("goodsId") ;
        int goodsId = Integer.parseInt(getGoodsId);
        Goods goods = presenter.getGoodsById(goodsId);
        Glide.with(GoodsDetailActivity.this)
                        .load(goods.getFirst_image())
                                .into(goodsImg);
        price.setText(String.valueOf(goods.getPrice()));
        unit.setText(goods.getUnit());
        Total.setText(String.valueOf(goods.getPrice()));
        Need.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s!=null && !s.toString().isEmpty()){
                    int num = Integer.parseInt(Need.getText().toString());
                    if (num<=1000){
                        Total.setText(String.valueOf(goods.getPrice() * num));
                    }else {
                        Total.setText(String.valueOf(goods.getPrice() * 1000));
                        Toast.makeText(GoodsDetailActivity.this, "超过购买数量", Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Total.setText("0");
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        Subtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String num = Need.getText().toString();
                int number = Integer.parseInt(num);
                if (number>1){
                    Need.setText(String.valueOf(number-1));
                    Total.setText(String.valueOf(goods.getPrice() * (number-1)));
                }else {
                    Toast.makeText(GoodsDetailActivity.this, "亲，不能再少了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String num = Need.getText().toString();
                int number = Integer.parseInt(num);
                if (number <= 1000){
                    Need.setText(String.valueOf(number+1));
                    Total.setText(String.valueOf(goods.getPrice() * (number+1)));
                }else {
                    Need.setText("1000");
                    Total.setText(String.valueOf(goods.getPrice()*1000));
                    Toast.makeText(GoodsDetailActivity.this, "超过购买数量", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取货品Id
                Intent intent = getIntent();
                String getGoodsId = intent.getStringExtra("goodsId") ;
                int goodsId = Integer.parseInt(getGoodsId);

                SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                String phone = sharedPreferences.getString("phone" , "");

                //获取备注
                String remark = "";


                String numb = Need.getText().toString().trim();
                String lId = String.valueOf(presenter.getLocalDefaultId(phone));
                if (!TextUtils.isEmpty(numb) && !TextUtils.isEmpty(lId)){
                    //获取默认地址Id
                    int localId = presenter.getLocalDefaultId(phone);
                    //获取数量
                    int num = Integer.parseInt(Need.getText().toString());
                    if (num<1){
                        Toast.makeText(GoodsDetailActivity.this, "商品数量不规范", Toast.LENGTH_SHORT).show();
                    }else {
                        if (localId != 0){
                            Intent intent1 = new Intent(GoodsDetailActivity.this , ClearingActivity.class);
                            intent1.putExtra("payGId" , goodsId);
                            intent1.putExtra("payLId" , localId);
                            intent1.putExtra("payRemark" , remark);
                            intent1.putExtra("payNum" , num);
                            startActivity(intent1);
                            bottomSheetDialog.dismiss();
                        }else {
                            Intent intent1 = new Intent(GoodsDetailActivity.this , LocalManagerActivity.class);
                            startActivity(intent1);
                            Toast.makeText(GoodsDetailActivity.this, "请创建默认地址", Toast.LENGTH_SHORT).show();
                        }

                    }
                }else {
                    Toast.makeText(GoodsDetailActivity.this, "请输入购买数量", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.show();
    }

    @Override
    public void showGoodsMessage(String imgTitle , double price , String unit , String goodsId ,
                                 String goodsName , String address , String freight , String userConcern ,
                                 String userName , String goodsText , String imgList) {
//        Bitmap bitmap = stringPathToBitmap(imgTitle);
//        if (bitmap != null){ // 设置顶部图片
//            TitlePhoto.setImageBitmap(bitmap);
//        }else {
//            TitlePhoto.setImageResource(R.drawable.add_photo);
//        }
        Glide.with(GoodsDetailActivity.this)
                .load(imgTitle)
                .error(R.drawable.focus_del)
                .into(TitlePhoto);
        String goodsPrice = String.valueOf(price);
        ShowPrice.setText(goodsPrice);
        ShowUnit.setText(unit);
        ShowId.setText(goodsId);
        ShowGoodsName.setText(goodsName);
        ShowLocal.setText(address);
        ShowLogistics.setText(freight);

        Glide.with(GoodsDetailActivity.this)
                        .load(userConcern)
                                .into(ShowConcern);

        ShowName.setText(userName);
        ShowDetails.setText(goodsText);
        imageList.clear();
        String[] imgPath =  convertJsonToArray(imgList);
        for (String img : imgPath){
            imageList.add(img);
        }
        if (imageList != null){
            imgAdapter();
            listPhotos.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            int size = imageList.size();
            ViewGroup.LayoutParams layoutParams = listPhotos.getLayoutParams();
            layoutParams.height = 620*size ;
            listPhotos.setLayoutParams(layoutParams);
        }
    }

    private static  String[] convertJsonToArray(String jsonString){
        String[] imgPathArray = null ;
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            imgPathArray = new String[jsonArray.length()] ;
            for (int i = 0 ; i < jsonArray.length() ; i++){
                imgPathArray[i] = jsonArray.getString(i) ;
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return imgPathArray ;
    }

    private void imgAdapter(){
        adapter = new ArrayAdapter<String>(this , R.layout.goods_img_list_item , R.id.b1 , imageList){
            public View getView(int position , View converView , ViewGroup parents){
                View view = super.getView(position, converView, parents);
                TextView textView = view.findViewById(R.id.b1);
                ImageView imageView = view.findViewById(R.id.goods_message_item);
                String imgPath = getItem(position);
                Glide.with(GoodsDetailActivity.this)
                        .load(imgPath)
                        .into(imageView);
                return view ;
            }


        };
    }
    public Bitmap stringPathToBitmap(String imagePath) {
        try {
            // 使用BitmapFactory.decodeFile方法将图片路径转换为Bitmap对象
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

            if (bitmap != null) {
                return bitmap;
            } else {
                // 图片加载失败处理
                // Log.e("ImageLoadError", "Failed to load image from path: " + imagePath);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            return null;
        }
    }


    private void showCallConfirmationDialog(String phoneNumber) {
        // 检查拨打电话的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CALL_PHONE},
                    1);
        } else {
            confirmCall(phoneNumber);
        }
    }
    // 确认拨打电话
    private void confirmCall(String phoneNumber) {
        new AlertDialog.Builder(this)
                .setTitle("拨打电话")
                .setMessage("您确定要拨打"+ phoneNumber +"这个电话吗？")
                .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse("tel:" + phoneNumber));
                        startActivity(callIntent);
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    //关于收藏的操作
    private void getCollect(){
        String type = "goods" ;//收藏类型
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");//收藏user
        Intent intent = getIntent();
        String getGoodsId = intent.getStringExtra("goodsId") ;
        int goodsId = Integer.parseInt(getGoodsId);
        String gId = String.valueOf(goodsId);//收藏id

        Collect collect = presenter.getCollect(gId,type,phone);
        addCollection.setChecked(collect != null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getCollect();
    }
}
